<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\UserEquityCertificate;
use app\common\model\UserEquityLog;
use app\common\model\User;
use think\Db;

/**
 * 用户权益管理接口
 */
class UserEquity extends Api
{
    // 无需登录的接口
    protected $noNeedLogin = [];
    // 无需鉴权的接口
    protected $noNeedRight = ['*'];
    
    /**
     * 获取用户权益证书列表
     *
     * @ApiMethod (GET)
     * @ApiParams (name="page", type="integer", required=false, description="页码，默认1")
     * @ApiParams (name="limit", type="integer", required=false, description="每页数量，默认10")
     */
    public function certificates()
    {
        $user_id = $this->auth->id;
        $page = $this->request->get('page/d', 1);
        $limit = $this->request->get('limit/d', 10);
        
        $total = UserEquityCertificate::where('user_id', $user_id)
            ->where('status', 1)
            ->count();
            
        $list = UserEquityCertificate::with(['product'])
            ->where('user_id', $user_id)
            ->where('status', 1)
            ->page($page, $limit)
            ->order('id', 'desc')
            ->select();
            
        $result = [
            'total' => $total,
            'list' => $list
        ];
        
        $this->success('获取成功', $result);
    }
    
    /**
     * 获取用户权益积分统计
     *
     * @ApiMethod (GET)
     */
    public function statistics()
    {
        $user_id = $this->auth->id;
        
        // 计算用户总权益积分
        $totalPoints = UserEquityCertificate::where('user_id', $user_id)
            ->where('status', 1)
            ->sum('points');
            
        // 获取最近5条权益积分变动记录
        $logs = Db::name('user_equity_log')
            ->where('user_id', $user_id)
            ->order('id', 'desc')
            ->limit(5)
            ->select();
            
        $result = [
            'total_points' => $totalPoints ?: 0,
            'recent_logs' => $logs
        ];
        
        $this->success('获取成功', $result);
    }
    
    /**
     * 获取用户权益积分详情
     * 
     * @ApiMethod (GET)
     * @ApiReturn ({"name":"total_points","type":"integer","description":"当前总积分"})
     * @ApiReturn ({"name":"account_balance","type":"integer","description":"账户余额（可用积分）"})
     * @ApiReturn ({"name":"locked_amount","type":"integer","description":"锁仓额度"})
     * @ApiReturn ({"name":"release_amount","type":"integer","description":"释放额度"})
     * @ApiReturn ({"name":"release_ratio","type":"string","description":"释放比例"})
     * @ApiReturn ({"name":"can_release","type":"boolean","description":"今日是否可释放"})
     */
    public function equity()
    {
        $user_id = $this->auth->id;
        
        // 获取用户信息
        $user = $this->auth->getUser();
        
        // 计算用户总权益积分（从权益证书中获取）
        $totalPoints = UserEquityCertificate::where('user_id', $user_id)
            ->where('status', 1)
            ->sum('points') ?: 0;
        
        // 账户余额（可用积分）- 从用户表的score字段获取
        $accountBalance = $user->score ?: 0;
        
        // 锁仓额度 - 从权益证书中获取锁定状态的积分
        $lockedAmount = Db::name('user_equity_certificate')
            ->where('user_id', $user_id)
            ->where('status', 1) // 有效状态
            ->sum('locked_points') ?: 0;
        
        // 获取系统配置的释放比例
        $releaseRatio = Db::name('config')
            ->where('name', 'equity_release_ratio')
            ->value('value') ?: 0.1; // 默认10%
            
        // 计算可释放额度 - 根据锁仓额度和释放比例
        $releaseAmount = intval($lockedAmount * floatval($releaseRatio));
        
        // 检查用户当日是否下单了助农商品
        $currentTime = time();
        $todayStart = strtotime(date('Y-m-d', $currentTime));
        $todayEnd = $todayStart + 86400 - 1;
        
        $hasAgricultureOrder = Db::name('order')
            ->where('user_id', $user_id)
            ->where('attribute_type', 3) // 助农抢购商品
            ->where('order_status', 1) // 已支付状态
            ->where('createtime', 'between', [$todayStart, $todayEnd])
            ->count() > 0;
        
        // 如果用户当日没有下单助农商品，释放额度为0
        if (!$hasAgricultureOrder) {
            $releaseAmount = 0;
        }
        
        $result = [
            'total_points' => $totalPoints,
            'account_balance' => $accountBalance,
            'locked_amount' => $lockedAmount,
            'release_amount' => $releaseAmount,
            'release_ratio' => floatval($releaseRatio) * 100 . '%', // 转换为百分比显示
            'can_release' => $hasAgricultureOrder && $releaseAmount > 0
        ];
        
        $this->success('获取成功', $result);
    }
    
    /**
     * 释放锁仓权益积分
     *
     * @ApiMethod (POST)
     */
    public function release()
    {
        $user_id = $this->auth->id;
        
        // 获取用户信息
        $user = Db::name('user')->where('id', $user_id)->find();
        if (!$user) {
            $this->error('用户不存在');
        }
        
        // 获取用户权益证书中的锁仓积分总额
        $lockedPoints = Db::name('user_equity_certificate')
            ->where('user_id', $user_id)
            ->where('status', 1) // 有效状态
            ->sum('locked_points');
        
        if ($lockedPoints <= 0) {
            $this->error('没有可释放的锁仓积分');
        }
        
        // 获取系统配置的释放比例和周期
        $releaseRatio = Db::name('config')->where('name', 'equity_release_ratio')->value('value');
        $releaseCycle = Db::name('config')->where('name', 'equity_release_cycle')->value('value');
        
        if (!$releaseRatio || !$releaseCycle) {
            $this->error('系统未配置释放参数');
        }
        
        // 默认释放比例为10%，周期为1天（86400秒）
        $releaseRatio = floatval($releaseRatio ?: 0.1);
        $releaseCycle = intval($releaseCycle ?: 86400);
        
        // 获取用户上次释放时间
        $lastReleaseTime = Db::name('user_equity_log')
            ->where('user_id', $user_id)
            ->where('memo', 'like', '%锁仓积分释放%')
            ->order('createtime desc')
            ->value('createtime');
        
        $currentTime = time();
        
        // 如果没有释放记录或者已经超过释放周期
        if (!$lastReleaseTime || ($currentTime - $lastReleaseTime) >= $releaseCycle) {
            // 检查用户当日是否下单了助农商品
            $todayStart = strtotime(date('Y-m-d', $currentTime));
            $todayEnd = $todayStart + 86400 - 1;
            
            $hasAgricultureOrder = Db::name('order')
                ->where('user_id', $user_id)
                ->where('attribute_type', 3) // 助农抢购商品
                ->where('order_status', 1) // 已支付状态
                ->where('createtime', 'between', [$todayStart, $todayEnd])
                ->count();
            
            if (!$hasAgricultureOrder) {
                // 用户当日没有下单助农商品，释放额度为0
                $this->error('您今日未购买助农商品，无法释放积分');
            }
            
            // 计算本次可释放的积分（根据锁仓额度和释放比例）
            $releasePoints = intval($lockedPoints * $releaseRatio);
            
            if ($releasePoints <= 0) {
                $this->error('本次可释放积分为0');
            }
            
            Db::startTrans();
            try {
                // 更新用户积分
                User::score($releasePoints, $user_id, '锁仓积分释放');
                
                // 减少锁仓额度
                // 按比例减少每个证书的锁仓积分
                $certificates = Db::name('user_equity_certificate')
                    ->where('user_id', $user_id)
                    ->where('status', 1)
                    ->where('locked_points', '>', 0)
                    ->select();
                
                $remainingToRelease = $releasePoints;
                
                foreach ($certificates as $cert) {
                    if ($remainingToRelease <= 0) {
                        break;
                    }
                    
                    // 计算当前证书可释放的积分
                    $certReleasePoints = min($remainingToRelease, $cert['locked_points']);
                    
                    // 更新证书锁仓积分
                    Db::name('user_equity_certificate')
                        ->where('id', $cert['id'])
                        ->setDec('locked_points', $certReleasePoints);
                    
                    $remainingToRelease -= $certReleasePoints;
                }
                
                // 记录权益积分日志
                Db::name('user_equity_log')->insert([
                    'user_id' => $user_id,
                    'points' => $releasePoints,
                    'before' => $user['score'],
                    'after' => $user['score'] + $releasePoints,
                    'memo' => '锁仓积分释放',
                    'createtime' => $currentTime
                ]);
                
                Db::commit();
                
                $this->success('积分释放成功', [
                    'release_points' => $releasePoints,
                    'current_score' => $user['score'] + $releasePoints,
                    'next_release_time' => date('Y-m-d H:i:s', $currentTime + $releaseCycle)
                ]);
                
            } catch (Exception $e) {
                Db::rollback();
                $this->error('积分释放失败: ' . $e->getMessage());
            }
        } else {
            // 计算下次可释放时间
            $nextReleaseTime = $lastReleaseTime + $releaseCycle;
            $this->error('释放周期未到', [
                'next_release_time' => date('Y-m-d H:i:s', $nextReleaseTime),
                'remaining_time' => $nextReleaseTime - $currentTime
            ]);
        }
    }
}